package com.java.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.system.entity.User;
import com.java.system.mapper.UserMapper;
import com.java.system.service.ILoginService;
import com.java.system.utils.JwtUtil;
import com.java.system.utils.Md5Utils;
import com.java.system.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisUtil redisUtil;
    @Override
    public String login(User user) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        String password= Md5Utils.code(user.getPassword());
        queryWrapper.eq(User::getUsername,user.getUsername());
        queryWrapper.eq(User::getPassword,password);
        User user1 = userMapper.selectOne(queryWrapper);

        if(user1!=null){
            String userId = user1.getId().toString();
            String jwt = JwtUtil.createJWT(userId);
            log.info(jwt);
            redisUtil.setCacheObject("login"+userId,user1);
            return jwt;
        }
        else {
            return null;
        }
    }

    @Override
    public User select(String id) {
        User user = userMapper.selectById(id);
        if(user!=null){
            return user;
        }
        else {
            return null;
        }
    }
}
